import { ref } from "vue";
import Map from "ol/Map";
import { Feature, View } from "ol";
import { Point, Polygon } from "ol/geom";
import { Style, Icon, Stroke, Fill } from "ol/style";
import ss from "../assets/images/bg03.svg";
import bg04 from "../assets/images/bg04.svg";
import { Vector as LayerVector } from "ol/layer";
import { Vector as SourceVector } from "ol/source";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { useEventBus } from "@vueuse/core";
import Cookies from "js-cookie";
import axios from "axios";

export const bus = useEventBus<any>("news");
const Tokenkey = "Admin-Token";
export const getToken = () => {
  // console.log("🚀 ~ Tokenkey:", Cookies.get(Tokenkey));
  return Cookies.get(Tokenkey);
};

if (!getToken()) {
  let path = window.location.href.includes("szly.lyj.jiangsu.gov.cn")
    ? "https://szly.lyj.jiangsu.gov.cn:8312/forestry-iam-work-internet-pc/login312"
    : "http://172.26.199.64:10001/forestry-iam-work-gov-pc/login312";
  window.location.href = path;
  
}
// 地图对象
export const olMap = ref<Map | null>(null);

export const FeatureIs = ref({
  show: false,
  x: -900,
  y: -900,
});

export const PageData = ref({
  districtCode: "",
  distrcitName: "",
  leaderPost: 1,
  keyWork: "",
  responsibility: "",
  leaderNum: 0,
  rangerNum: 0,
  onlineLeaderNum: 0,
  onlinePatrolNum: 0,
  leaders: [],
  responseArea: {
    name: "",
    area: "",
    forestCoverage: "",
    treeCoverage: "",
    forestArea: "",
    provincePublicWelfareForestArea: "",
    cityPublicWelfareForestArea: "",
    wetLandArea: "",
    wetLandProtectArea: "",
    protectedArea: "",
    protectedAreaNum: "",
    theGeom: {
      type: "MultiPolygon",
      coordinates: [],
    },
  },
  leaderWork: {
    patrolList: [],
    leaderOrderList: [],
    meetingList: [],
  },
  leaderSystemOperation: [],

  onlineRate: [],
  rangerOnlinePosition: [],
  leaderOnlinePosition: [],
});

export const updatePageData = async (code: number) => {
  const mode = import.meta.env.MODE;
  const apiBaseUrl =
    mode === "production" ? window.location.origin : "/java-server";

  // 使用 fetch 发起 GET 请求并添加自定义请求头
  axios
    .get(`${apiBaseUrl}/prod-api/work/statistics/screen/${code}`, {
      headers: {
        // Authorization: "Bearer " + "c25b7a53-4df7-4c8a-9eee-d84456642279", // 示例：添加授权头

        Authorization: "Bearer " + getToken(), // 示例：添加授权头
        //   "Custom-Header": "CustomValue", // 示例：添加自定义请求头
      },
      params: {
        // districtCode: "+" + code.toString() + "",
      },
    })
    .then(({ data }) => {
      // 处理响应数据
      if (data.code === 200 && data.data) {
        const dataRef = {
          districtCode: data.data.districtCode || "",
          distrcitName: data.data.distrcitName || "",
          leaderPost: data.data.leaderPost || 1,
          keyWork: data.data.keyWork || "",
          responsibility: data.data.responsibility || "",
          leaderNum: data.data.leaderNum || 0,
          rangerNum: data.data.rangerNum || 0,
          onlineLeaderNum: data.data.onlineLeaderNum || 0,
          onlinePatrolNum: data.data.onlinePatrolNum || 0,
          leaders: data.data.leaders || [],
          responseArea: data.data.responseArea || {
            name: "",
            area: "",
            forestCoverage: "",
            treeCoverage: "",
            forestArea: "",
            provincePublicWelfareForestArea: "",
            cityPublicWelfareForestArea: "",
            wetLandArea: "",
            wetLandProtectArea: "",
            protectedArea: "",
            protectedAreaNum: "",
            theGeom: {
              type: "MultiPolygon",
              coordinates: [],
            },
          },
          leaderWork: data.data.leaderWork || {
            patrolList: [],
            leaderOrderList: [],
            meetingList: [],
          },
          leaderSystemOperation: data.data.leaderSystemOperation || [],

          onlineRate: data.data.onlineRate || [],
          rangerOnlinePosition: data.data.rangerOnlinePosition || [],
          leaderOnlinePosition: data.data.leaderOnlinePosition || [],
        };
        PageData.value = dataRef;

        bus.emit(PageData.value);

        addpolygon();
        createPoint();
      }
    })
    .catch((error) => {
      // 处理请求错误
      console.error("请求出错:", error);
    });
};

export const currectData = ref({ code: 3201, name: "南京市" });
export const layer = new LayerVector({
  source: new SourceVector(),
});
export const optionsList = ref([
  {
    code: 3201,
    name: "南京市",
    children: [
      { code: 3201, name: "南京市 " },
      { code: 320111, name: "浦口区 " },
      { code: 320113, name: "栖霞区 " },
      { code: 320114, name: "雨花台区" },
      { code: 320115, name: "江宁区 " },
      { code: 320116, name: "六合区 " },
      { code: 320117, name: "溧水区 " },
      { code: 320118, name: "高淳区 " },
    ],
  },
  { code: 3202, name: "无锡市" },
  { code: 3203, name: "徐州市" },
  { code: 3204, name: "常州市" },
  { code: 3205, name: "苏州市" },
  { code: 3206, name: "南通市" },
]);

export const handleSelect = (
  key: number,
  ki: { code: number; name: string }
) => {
  currectData.value = ki;
  updateData(key);
};
export const updateData = (value: number) => {
  updatePageData(value);

  // fetch("./datas/" + value + ".json")
  //   .then((response) => response.json())
  //   .then((json) => {
  //     if (json.list.length > 0) {
  //       PageData.value = json.list[0];
  //       bus.emit(PageData.value);
  //     }

  //     addpolygon();
  //     createPoint();
  //   });
};

export const initDataFn = async () => {
  const mode = import.meta.env.MODE;
  const apiBaseUrl =
    mode === "production" ? window.location.origin : "/java-server";

  const { data } = await axios.get(
    `${apiBaseUrl}/prod-api/ebsystem/user/getInfo`,
    {
      headers: {
        // Authorization: "Bearer " + "c25b7a53-4df7-4c8a-9eee-d84456642279", // 示例：添加授权头

        Authorization: "Bearer " + getToken(), // 示例：添加授权头
        //   "Custom-Header": "CustomValue", // 示例：添加自定义请求头
      },
      params: {
        // districtCode: "+" + code.toString() + "",
      },
    }
  );
  if (data.code === 200 && data.data && data.data.dept) {
    const { districtCode } = data.data.dept;
    updateData(districtCode);
  }

  const result = await insertDataIntoTree(0);
  optionsList.value = result;
};

const insertDataIntoTree = async (code: number): Promise<any[]> => {
  const mode = import.meta.env.MODE;
  let result = [];
  const apiBaseUrl =
    mode === "production" ? window.location.origin : "/java-server";

  const { data } = await axios.get(
    `${apiBaseUrl}/prod-api/ebsystem/areaCode/localList/${code}`,
    {
      headers: {
        // Authorization: "Bearer " + "c25b7a53-4df7-4c8a-9eee-d84456642279", // 示例：添加授权头
        Authorization: "Bearer " + getToken(), // 示例：添加授权头
        //   "Custom-Header": "CustomValue", // 示例：添加自定义请求头
      },
      params: {
        // districtCode: "+" + code.toString() + "",
      },
    }
  );
  if (data.code === 200 && data.list) {
    if (code === 0) {
      currectData.value = data.list[0];
      // const _result = await insertDataIntoTree(data.list[0].code);

      result = [
        { code: data.list[0].code, name: data.list[0].name },

        // ..._result,
      ];
    } else {
      if (data.list.length > 0) {
        // data.list.forEach(async (item: any) => {
        //   const _result = await insertDataIntoTree(item.code);
        //   // console.log(_result);
        //   // item["children"];
        //   if (_result.length > 0) {
        //     item["children"] = [
        //       { code: item.code, name: item.name },
        //       ..._result,
        //     ];
        //   }
        // });

        result = data.list;
      }
    }
  }
  return result;
};
let polygonSource = new VectorSource();
const FeatureList = ref<Feature<Point>[]>([]);
// 创建点位
export const createPoint = () => {
  // @ts-ignore
  polygonSource.removeFeatures(FeatureList.value);
  FeatureList.value = [];
  // PageData.value.rangerOnlinePosition.forEach(item => {
  //     const style = new Style({
  //         image: new Icon({ src: ss, }),
  //     });
  //     // 创建一个Feature，并设置好在地图上的位置
  //     var anchor = new Feature({
  //         geometry: new Point([item.lon, item.lat]),
  //         id: item.name,
  //         datalist: item
  //     });
  //     // 设置样式，在样式中就可以设置图标
  //     anchor.setStyle(style);
  //     FeatureList.value.push(anchor)
  // })
  PageData.value.leaderOnlinePosition.forEach((item) => {
    const style = new Style({
      image: new Icon({ src: ss }),
    });
    // 创建一个Feature，并设置好在地图上的位置
    var anchor = new Feature({
      geometry: new Point([item.lon, item.lat]),
      id: item.name,
      datalist: item,
    });
    // 设置样式，在样式中就可以设置图标
    anchor.setStyle(style);
    FeatureList.value.push(anchor);
  });
  PageData.value.rangerOnlinePosition.forEach((item) => {
    const style = new Style({
      image: new Icon({ src: bg04 }),
    });
    // 创建一个Feature，并设置好在地图上的位置
    var anchor = new Feature({
      geometry: new Point([item.lon, item.lat]),
      id: item.name,
      datalist: item,
    });
    // 设置样式，在样式中就可以设置图标
    anchor.setStyle(style);
    FeatureList.value.push(anchor);
  });

  // @ts-ignore
  polygonSource.addFeatures(FeatureList.value);
};

export const renName = ref("");
export const polygonLayer = new VectorLayer({
  source: polygonSource,
});
const zooms = {
  2: 7.5,
  4: 9,
};
let polygonFeature: any[] = [];
export const addpolygon = () => {
  polygonFeature.forEach((item) => {
    polygonSource.removeFeature(item);
  });
  polygonFeature = [];
  // let polygonData = [[113.90314496806384, 32.55119145031371], [113.90323996014925, 32.55090529821837], [113.90357286938732, 32.551129876009725], [113.90367281288155, 32.550699598512765], [113.90333990487254, 32.55047502105481], [113.90368767113986, 32.550267223522305], [113.90369757646867, 32.54997897350877], [113.90395035190585, 32.5500573277816], [113.90412794770106, 32.54984533440191], [113.90438072322067, 32.549923687809084], [113.9043104942128, 32.54948921561037], [113.90448066108058, 32.54949340928286], [113.90451036815635, 32.548628658438524], [113.9047755173468, 32.54834669792548], [113.90455245100283, 32.547403594497126], [113.90490267737313, 32.547123730008416], [113.9052430024095, 32.5471321149814], [113.90552299189441, 32.54641777644994], [113.90620363718125, 32.54643454179698], [113.9063812200704, 32.546222544369044], [113.90689170329237, 32.54623511517295], [113.90715436459246, 32.54602521144418], [113.9077474548084, 32.54611193626682], [113.90792503354562, 32.54589993638597], [113.90843798782572, 32.5458404379363], [113.90878819653909, 32.54556056144315], [113.90937881459087, 32.545719341400854], [113.90961181459905, 32.546374187481184], [113.90970430901407, 32.5461600917095], [113.91012971271965, 32.54617055626247], [113.90989670926501, 32.54551571092959], [113.91025926548397, 32.544875514957695], [113.91001390995845, 32.544580984898275], [113.91035422704749, 32.54458935545819], [113.91036163846013, 32.544373166390464], [113.91028644140913, 32.544082821772825], [113.9101162838133, 32.54407863657368], [113.91012863683154, 32.543718321507605], [113.90995847994863, 32.54371413613639], [113.90996589206036, 32.543497947119434], [113.90979820644107, 32.54342169855699], [113.90981303118669, 32.54298932055956], [113.91007320554333, 32.542851472659976], [113.91000048086588, 32.54248906492205], [113.91026312379994, 32.54227915347875], [113.91027794566644, 32.541846775212704], [113.91044809907875, 32.541850959939126], [113.91037043297916, 32.5416326784409], [113.91097090813003, 32.54150319725995], [113.91098325651244, 32.54114288175522], [113.9112409542698, 32.541077094085765], [113.91125083196881, 32.54078884159088], [113.91185376938945, 32.54058729259663], [113.91195365790371, 32.540157004783815], [113.9123063013929, 32.53980505305578], [113.91258374028897, 32.53916275651838], [113.91310405761527, 32.5388870466459], [113.9131089930907, 32.53874292009655], [113.91285623906342, 32.538664585592834], [113.91287351431106, 32.538160142753], [113.91253322066216, 32.538151780473626], [113.91254062502054, 32.53793559073944], [113.91228293717215, 32.53800138170718], [113.9123556690464, 32.53836378868], [113.91218552190357, 32.538359606931365], [113.91202524898776, 32.53806717212243], [113.91201784335712, 32.538283361746856], [113.91176262296501, 32.53827708836587], [113.91183782158076, 32.53856743232279], [113.91132737935567, 32.53855488421624], [113.91140504579953, 32.53877316519334], [113.91114735486948, 32.53883895362658], [113.91104993397039, 32.539197177600286], [113.91070716730486, 32.53926087325699], [113.91069728844909, 32.5395491256738], [113.91104499511974, 32.53934130385884], [113.91103264783891, 32.539701619487815], [113.91077742367277, 32.539695343865304], [113.91077248429225, 32.539839470075314], [113.91051478989218, 32.539905256987446], [113.91049997026673, 32.54033763548378], [113.91032981970007, 32.54033345099976], [113.91025709515614, 32.53997104334702], [113.91008694531986, 32.53996685857608], [113.90999198903864, 32.54025301829684], [113.90965910028163, 32.54002845867007], [113.90959379046302, 32.53944986171187], [113.90993408806226, 32.53945823224086], [113.90992420666178, 32.53974648443799], [113.91009188581964, 32.53982273246239], [113.91027685585965, 32.53939453877603], [113.91011658778956, 32.53910210183425], [113.91036934016415, 32.53918044178133], [113.91037674999994, 32.53896425252454], [113.91004139450976, 32.53881175717589], [113.90969121741807, 32.539091639248085], [113.90841016459281, 32.539204368776986], [113.90719193093331, 32.53996774517776], [113.90709449295646, 32.54032596499882], [113.90692434295984, 32.54032177590824], [113.90693176137525, 32.5401055873951], [113.90675913888862, 32.540173460936586], [113.90683184927668, 32.54053586976365], [113.90708954757307, 32.54047009069239], [113.90716967743691, 32.54061631086422], [113.90759258166594, 32.54069884529187], [113.90758763700734, 32.5408429710448], [113.90715731407454, 32.54097662509968], [113.90697232570167, 32.54140481300036], [113.90712516829994, 32.5419134419955], [113.90668494683062, 32.54233534528869], [113.9065850301948, 32.542765627108906], [113.90632485136695, 32.54290346746939], [113.9055071961949, 32.5443979255134], [113.90500167350972, 32.54424122439846], [113.90497445098079, 32.54503391359986], [113.90463165884752, 32.54509759100395], [113.90445159921997, 32.54538164848305], [113.90402372590263, 32.545443227524686], [113.90401629899581, 32.545659415259095], [113.90367597991103, 32.54565102730171], [113.9030151535793, 32.54505774853975], [113.90258975798623, 32.54504726023392], [113.90249724846049, 32.545261349837354], [113.90215693136729, 32.54525295785942], [113.90224944167088, 32.54503886855521], [113.901743922261, 32.54488215445498], [113.90158862952849, 32.544445583073994], [113.901075681114, 32.54450505374248], [113.9009831687481, 32.544719142060764], [113.90100051440794, 32.544214705374465], [113.90040001053524, 32.54434413683037], [113.9003223676838, 32.54412585053409], [113.9001522116122, 32.544121651846474], [113.90024472516818, 32.54390756420614], [113.89998949171041, 32.543901265968344], [113.8999845342963, 32.544045390609845], [113.89973177942635, 32.543967029517425], [113.89972682158798, 32.544111154122184], [113.89947654592453, 32.54396073022827], [113.8995541865722, 32.54417901691967], [113.89938155131196, 32.54424687946321], [113.89921139516392, 32.54424267948866], [113.89930391104731, 32.544028592688875], [113.89904867747491, 32.54402229252068], [113.89896855867552, 32.543876067847236], [113.89895120187934, 32.544380503588535], [113.8986959673967, 32.54437420264413], [113.8988537253938, 32.54473871451615], [113.89851341144814, 32.544730312796396], [113.8985860903678, 32.545092724385675], [113.89952195788341, 32.545115826590035], [113.9000448253185, 32.54476811329713], [113.90106329156315, 32.5448653656753], [113.90164150097074, 32.545384493006345], [113.90231222797706, 32.54568952874086], [113.90256994386186, 32.54562376009215], [113.9031456906539, 32.54621494376071], [113.9033984552233, 32.54629329851553], [113.9032985171086, 32.54672357626872], [113.9037140168832, 32.547022312824126], [113.90344886880894, 32.547304271179684], [113.90343896370348, 32.547592521247935], [113.90360665068957, 32.54766877840982], [113.90357198348109, 32.54867765367136], [113.90281119422364, 32.548514650298486], [113.9023758734501, 32.54879241003964], [113.90201572256113, 32.54936051614028], [113.90215368103873, 32.55030152413928], [113.90249401717941, 32.55030991727787], [113.90239406871913, 32.5507401935432], [113.90256423763823, 32.55074438995211], [113.90264189039584, 32.55096267534089], [113.90264932211105, 32.55074648807037], [113.9029070525999, 32.55068071963754], [113.90289466742465, 32.55104103184189], [113.903154875479, 32.55090320049075], [113.90314496806384, 32.55119145031371]]
  let polygonData = PageData.value.responseArea.theGeom.coordinates;
  let pol: any = { len: 0, value: null };
  polygonData.forEach((item: any) => {
    const plo = new Polygon(item);
    if (item && item[0]) {
      if (pol.len < item[0].length) {
        pol.len = item[0].length;
        pol.value = plo;
      }
    }

    const ploh = new Feature({
      geometry: plo,
    });
    polygonFeature.push(ploh);
    let polygonStyle = new Style({
      stroke: new Stroke({
        color: "#18b343",
        width: 4,
      }),
      fill: new Fill({
        color: "#18b34342",
      }),
    });
    // 添加线的样式
    ploh.setStyle(polygonStyle);
    if (olMap.value) {
      polygonSource.addFeature(ploh);
    }
  });

  // 计算多边形的中心点
  var center = pol.value?.getInteriorPoint().getCoordinates();
  if (center && olMap.value) {
    const zoom = zooms[currectData.value.code.toString().length] || 7.5;
    olMap.value.getView().setCenter(center);
    olMap.value.getView().setZoom(zoom);
    // olMap.value.getView().getZoom()
  }
};

export const initMap = () => {
  if (olMap.value) {
    olMap.value.addLayer(polygonLayer);
  }
};
